#!/usr/bin/env bash

# This wrapper script is necessary in order to avoid polluting the build
# systems with Android-specific quirks.

output_type=executable
output_path=a.out

runtime=c
case "$0" in
  *++)
    runtime=cxx
    ;;
esac

argv=()
while [[ $# > 0 ]]; do
  arg="$1"

  case "$arg" in
    -E)
      output_type=code
      ;;
    -c)
      output_type=object
      ;;
    -shared)
      output_type=shlib
      ;;
    -o)
      argv+=("-o")
      shift

      arg="$1"

      output_path="$arg"
      ;;
  esac

  argv+=("$arg")
  shift
done

base_argv=("-target" "@target@" "-no-canonical-prefixes")
case $output_type in
  code|object)
    base_argv+=("--sysroot" "@toolroot@/sysroot")
    if [[ $runtime = cxx ]]; then
      base_argv+=("-nostdinc++")
      base_argv+=("-I@ndkroot@/sources/cxx-stl/llvm-libc++/include")
      base_argv+=("-I@ndkroot@/sources/cxx-stl/llvm-libc++abi/include")
    fi
    ;;
  executable|shlib)
    base_argv+=("-Wl,-rpath-link=@toolroot@/sysroot/usr/lib/@tooltriplet@/@api@")
    if [[ $runtime = cxx ]]; then
      base_argv+=("-nostdlib++")
      for name in @cxxlibs@; do
        base_argv+=("@toolroot@/sysroot/usr/lib/@tooltriplet@/lib$name.a")
      done
    fi
    base_argv+=("@toolroot@/lib64/clang/@clang_version@/lib/linux/@clang_arch@/libunwind.a")
    base_argv+=("-lc")
    ;;
esac
if [[ $output_type = executable ]]; then
  base_argv+=("-Wl,-pie")
fi

"@driver@" "${base_argv[@]}" "${argv[@]}" || exit $?

case $output_type in
  executable|shlib)
    "@elf_cleaner@" --api-level @api@ --quiet "$output_path" || exit $?
    ;;
esac

exit 0
